/**
 * @author zhounan 
 * @date 2024年6月5日
 * @version V1.0
 */
package org.zn.etl.jdbc;

import java.util.Objects;

import org.apache.commons.lang3.StringUtils;

/**
 * @author zhounan 
 * @date 2024年6月5日
 * @version V1.0
 */
public class PGUpsert  extends Upsert{
	
	/**
	  INSERT INTO ${tableName} ( ${columns} )\r\n"
				VALUES ( ${values}  )\r\n"
			ON CONFLICT (conflict_target)\r\n"
				DO UPDATE SET  ${uset} " 
	 */

	
	protected String buildSql() {
		
		StringBuilder sb=new StringBuilder(INSERT);
		
		if(StringUtils.isNotEmpty(schema)) {
			sb.append(schema).append(".");
		}
		
		sb.append(tableName).append(" (");
	
		StringBuilder placeholders=new StringBuilder();
		
		for (String col : columns) {
			sb.append(col).append(",");
			placeholders.append("?,");
		}
		
		sb.deleteCharAt(sb.length()-1);
		placeholders.deleteCharAt(placeholders.length()-1);
		
		sb.append(" ) ");
		sb.append(" VALUES (");
		sb.append(placeholders).append(")");
		sb.append(" ON CONFLICT ");
		sb.append(" (").append(pk).append(")") ;
		
		sb.append(" DO UPDATE SET ");
		
		for (String col : columns) {
			if(Objects.equals(pk, col) )  continue;
			sb.append(col).append("=").append("?,");
		}
		
		sb.deleteCharAt(sb.length()-1);
		return sql=sb.toString();
			
	}



}
